﻿#include "threadforcurl.h"
#include <QDebug>

namespace Curl {

CurlTask::CurlTask(QJsonObject allvalue){
    m_all = allvalue;
}

CurlTask::~CurlTask()
{

}

void CurlTask::on_readoutput()
{
//    qDebug()<<process->readAllStandardOutput();
}

void CurlTask::on_readerror()
{
//    qDebug()<<process->readAllStandardError().split(' ').last();
}

void CurlTask::on_finished(int exitCode,QProcess::ExitStatus exitStatus)
{

    qDebug()<<exitCode<<exitStatus;
}

void CurlTask::on_errorOccurred(QProcess::ProcessError error)
{
    qDebug()<<error;
}

void CurlTask::run()
{
    QSharedPointer<QProcess> process(new QProcess);
    connect(process.data(), &QProcess::readyReadStandardOutput,[&](){
        m_all.insert("curl",1);
        m_all.insert("url",QString::fromUtf8(process->readAllStandardOutput()));
//        m_all.insert("status",QString::fromUtf8(process->readAllStandardOutput()));
        emit someData(m_all);
    });
    connect(process.data(), &QProcess::readyReadStandardError, [&](){
        m_all.insert("curl",2);
        if(m_all.value("status").toString().contains("100"))
            return;
        QByteArray temp = process->readAllStandardError();
        m_all.insert("statusValue",QString::fromUtf8(temp));
        m_all.insert("status",QString::fromUtf8(temp.split(' ').last()).replace("\r","").replace("\n",""));
        emit someData(m_all);
    });
//    connect(process.data(), SIGNAL(finished(int, QProcess::ExitStatus)), this , SLOT(on_finished(int,QProcess::ExitStatus)));
//    connect(process.data(), SIGNAL(errorOccurred(QProcess::ProcessError)) , this , SLOT(on_errorOccurred(QProcess::ProcessError)));
//    sV.insert("author", m_meMail);
//    sV.insert("recipient", recipient);
//    sV.insert("timestamp", timestamp);
//    sV.insert("message", file.fileName()+"|"+var);
//    sV.insert("filePath", var);
//    sV.insert("type", "2");
//    sV.insert("answer", "1");
//    value.insert("serverPath","http://"+m_piIp+":8080/");
//    qDebug()<<m_all;
    QStringList args;
    args.append("--progress-bar");
    args.append("--upload-file");
    args.append(m_all.value("filePath").toString());
    args.append(m_all.value("serverPath").toString());
    args.append("-H");
    args.append("Max-Days:1");
    process->start(m_all.value("cmdPath").toString(),args);
    process->waitForFinished();
    m_all.insert("curl",0);
    emit someData(m_all);
}

Controller::Controller() {
    pool = new QThreadPool;
    pool->setMaxThreadCount(3);
}

void Controller::addNewTask(QJsonObject value)
{
    CurlTask *ptr = new CurlTask(value);
    connect(ptr,SIGNAL(someData(QJsonObject)),this,SLOT(someData(QJsonObject)));
    pool->start(ptr);
}

void Controller::someData(QJsonObject value)
{
    emit getReturn(value);
}
}
